from flask.views import MethodView
from flask import jsonify, request, g
from app.extensions import db
from app.dbmodel import DeviceInfo
from flask import current_app
import csv,os,json
from datetime import datetime

#
#       设备信息
#           GET方法
#获取单个设备信息GET    /api/deviceInfo/<int:deviceInfo_id>
#获取全量设备信息GET    /api/deviceInfo/all
#           POST方法
#添加单个设备信息POST   /api/deviceInfo/
#更新单个设备信息POST   /api/deviceInfo/<int:deviceInfo_id>
#批量添加设备信息POST   /api/deviceInfo/upload
#           DELETE方法
#删除设备信息DELETE     /api/deviceInfo/<int:deviceInfo_id>
class DeviceInfoAPI(MethodView):

    __methods__ = ["GET","POST","DELETE"]

    def get(self, deviceInfo_id):

        # 全量查询
        if deviceInfo_id == 'all':
            data       = []
            deviceInfoAll = DeviceInfo.query.all()
            count      = DeviceInfo.query.count()
            for item in deviceInfoAll:
                item_dict={'id':item.id,'Node':item.Node,'SubNode':item.SubNode,'DevGroup':item.DevGroup,'DevIp':item.DevIp,'DevName':item.DevName,
                            'DevIPv6':item.DevIPv6,'DevIpmi':item.DevIpmi,'DevNote':item.DevNote}
                data.append(item_dict)
            data = {'code':0, 'msg':'', 'count':count, 'data':data}
            return jsonify(data)

        # 分页查询
        if deviceInfo_id == None:
            page       = request.args.get('page', default=1)
            limit      = request.args.get('limit', default=20)
            data       = []
            pagination = DeviceInfo.query.paginate(int(page),int(limit),error_out=False)
            count      = DeviceInfo.query.count()
            for item in pagination.items: 
                item_dict={'id':item.id,'Node':item.Node,'SubNode':item.SubNode,'DevGroup':item.DevGroup,'DevIp':item.DevIp,'DevName':item.DevName,
                            'DevIPv6':item.DevIPv6,'DevIpmi':item.DevIpmi,'DevNote':item.DevNote}
                # data.append(item.get_info())
                data.append(item_dict)
            data = {'code':0, 'msg':'', 'count':count, 'data':data}
            return jsonify(data)
        # 单台查询
        dev = DeviceInfo.query.get(int(deviceInfo_id))
        if dev:
            return dev.get_info()
        else:
            return jsonify({"status":"1", "result":"None"})
        
    def post(self, deviceInfo_id):
        if deviceInfo_id == None:   
            # 新增设备信息
            Node     = request.form.get('Node')
            SubNode  = request.form.get('SubNode')
            DevGroup = request.form.get('DevGroup')
            DevIp    = request.form.get('DevIp')
            DevName  = request.form.get('DevName')
            DevIPv6  = request.form.get('DevIPv6')
            DevIpmi  = request.form.get('DevIpmi')
            DevNote  = request.form.get('DevNote')
            device_info = DeviceInfo(Node=Node,SubNode=SubNode,DevGroup=DevGroup,DevIp=DevIp,DevName=DevName,DevIPv6=DevIPv6,DevIpmi=DevIpmi,DevNote=DevNote)
            db.session.add(device_info)
            db.session.commit()
            count       = DeviceInfo.query.count()
            if DeviceInfo.query.get(count) == device_info:
                return jsonify({"code":"0","status":"0","result":"this ok"})
            else: 
                return jsonify({"code":"1","status":"1","result":"error"})
        elif deviceInfo_id.isdecimal():
            # 更新设备信息
            Node     = request.form.get('Node')
            SubNode  = request.form.get('SubNode')
            DevGroup = request.form.get('DevGroup')
            DevIp    = request.form.get('DevIp')
            DevName  = request.form.get('DevName')
            DevIPv6  = request.form.get('DevIPv6')
            DevIpmi  = request.form.get('DevIpmi')
            DevNote  = request.form.get('DevNote')
            dev = DeviceInfo.query.get(int(deviceInfo_id))
            dev.Node, dev.SubNode, dev.DevGroup, dev.DevIp, dev.DevName, dev.DevIPv6, dev.DevIpmi, dev.DevNote \
            = Node, SubNode, DevGroup, DevIp, DevName, DevIPv6, DevIpmi, DevNote 
            info = dev.get_info()
            try:
                db.session.commit()
                return jsonify({"code":"0",
                            'msg':'success',
                            "status":"0",
                            "result":"ok",
                            "data": info})
            except Exception:
                db.session.rollback()
        elif deviceInfo_id == 'upload' :
            # 上传文件，批量新增设备信息
            print(current_app.config['UPLOAD_FOLDER'])
            f = request.files.get('file')
            filename_list = f.filename.split('.')
            file_suffix = datetime.utcnow().strftime('%Y%m%d%H%M%S')
            filename_new = '.'.join(filename_list[:-1]) + '.' + file_suffix + '.' + filename_list[-1]
            folder = current_app.config['UPLOAD_FOLDER']
            file_path = os.path.join(folder,filename_new)
            f.save(file_path)
            file_size = os.path.getsize(file_path)
            file_path_real = os.path.realpath(file_path)
            count_old = DeviceInfo.query.count()
            with open(file_path_real,'r',encoding='gbk') as file_csv:
                reader = csv.DictReader(file_csv,dialect ='excel')   #dialect ='excel'
                for row in reader:
                    print(row)
                    Node     = row['Node']
                    SubNode  = row['SubNode']
                    DevGroup = row['DevGroup']
                    DevName  = row['DevName']
                    DevIp    = row['DevIp']
                    DevIPv6  = row['DevIPv6']
                    DevIpmi  = row['DevIpmi']
                    DevNote  = row['DevNote']
                    #dev_exist = DeviceInfo.query.filter(DeviceInfo.DevIp==DevIp).first()
                    device_info = DeviceInfo(Node=Node,SubNode=SubNode,DevGroup=DevGroup,DevIp=DevIp,DevName=DevName,DevIPv6=DevIPv6,DevIpmi=DevIpmi,DevNote=DevNote)
                    db.session.add(device_info)
                    #if dev_exist == None:
                    try:
                        #device_info = DeviceInfo(DevGroup=DevGroup,DevIp=DevIp,DevName=DevName,DevIPv6=DevIPv6,VIPv4=VIPv4,VIPv6=VIPv6,DevIpmi=DevIpmi,DevNote=DevNote)
                        db.session.commit()
                    except Exception:
                        db.session.rollback()      
                    finally:
                        #db.session.close()
                        pass
            print(reader.line_num)
            num = reader.line_num
            count_new = DeviceInfo.query.count()
            print(count_old)
            print(count_new)
            print(count_new - count_old + 1)
            if count_new - count_old + 1 == num :
                return jsonify({"code":"0", 
                                "msg":"sucess", 
                                "status":"0",
                                "result":"this ok",
                                "data":{
                                    "文件名称": filename_new,
                                    "文件大小": file_size,
                                    "文件路径": file_path_real,
                                    "导入数量": num
                                    # "MD5":""
                            }})
            else:
                return jsonify({'code':'1', 'msg':'error',"status":"1","result":"error"})
            
        return jsonify({'code':'1', 'msg':'error',"status":"1","result":"error"})

    def delete(self, deviceInfo_id):
        if deviceInfo_id.isdecimal():
            dev = DeviceInfo.query.get(int(deviceInfo_id))
            info = dev.get_info()
            db.session.delete(dev)
            try:
                db.session.commit()
                return jsonify({"code":"0",
                            'msg':'success',
                            "status":"0",
                            "result":"ok",
                            "data": info})
            except Exception:
                db.session.rollback()
            finally:
                pass
            
        return jsonify({"code":"1",'msg':'this api is not exist',"status":"1","result":"error"})
